﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
using CLEXA.DataContracts;
using CLEXA.SurfaceClient.Functions;

namespace CLEXA.SurfaceClient.ViewModel
{
    public class DatabaseEditVM : VMBase
    {
        private readonly IDatabaseEdit facade;
        private readonly int databaseId;
        private readonly int userId;
        private string connectionString;
        private string connectionStringMessage;
        private readonly RelayCommand save;
        private readonly RelayCommand cancel;

        public string ConnectionString
        {
            get { return connectionString; }
            set
            {
                if (connectionString != value)
                {
                    connectionString = value;
                    RaisePropertyChanged("ConnectionString");
                    save.RaiseCanExecuteChanged();
                }
            }
        }

        public string ConnectionStringMessage
        {
            get { return connectionStringMessage; }
            private set
            {
                if (connectionStringMessage != value)
                {
                    connectionStringMessage = value;
                    RaisePropertyChanged("ConnectionStringMessage");
                }
            }
        }

        public ICommand Save
        {
            get { return save; }
        }

        public ICommand Cancel
        {
            get { return cancel; }
        }

        public DatabaseEditVM(IDatabaseEdit facade, int databaseId)
        {
            this.facade = facade;
            this.databaseId = databaseId;
            this.userId = facade.Databases[databaseId].UserId;
            this.connectionString = facade.Databases[databaseId].ConnectionString;
            this.save = new RelayCommand(DoSave, CanSave);
            this.cancel = new RelayCommand(DoCancel);
            this.save.CanExecuteChanged += Save_CanExecuteChanged;
        }

        private void Save_CanExecuteChanged(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(connectionString))
            {
                ConnectionStringMessage = "Please enter a connection string.";
            }
            else
            {
                ConnectionStringMessage = null;
            }
        }

        private void DoSave()
        {
            this.facade.UpdateDatabase(new DatabaseData(databaseId, userId, connectionString));
            this.facade.ClosePopUp();
        }

        private bool CanSave()
        {
            return !string.IsNullOrWhiteSpace(connectionString);
        }

        private void DoCancel()
        {
            this.facade.ClosePopUp();
        }
    }
}
